package kiwi.core.services.search.solr.program.parser.model;

import kiwi.core.api.triplestore.ResourceService;
import kiwi.core.api.triplestore.TripleStore;
import kiwi.core.model.rdf.KiWiLiteral;
import kiwi.core.model.rdf.KiWiResource;
import kiwi.core.model.rdf.KiWiTriple;
import kiwi.core.model.rdf.KiWiUriResource;

import java.util.*;

/**
 * User: Thomas Kurz
 * Date: 25.03.11
 * Time: 14:16
 */
public class Path {
	private List<String> uris = new ArrayList<String>();
	private String type;

	private static final Map<String,String> TYPE_PREFIX;
	static {
		TYPE_PREFIX = new HashMap<String,String>();
		TYPE_PREFIX.put("STRING","s");
		TYPE_PREFIX.put("TEXT","t");
		TYPE_PREFIX.put("LONG","l");
		TYPE_PREFIX.put("DOUBLE","d");
		TYPE_PREFIX.put("DATE","x");
		TYPE_PREFIX.put("URI","u");
	}

	public List<String> getValue(TripleStore triplestore, KiWiResource r, ResourceService resourceService) {
		//get triples
		List<String> l = new ArrayList<String>();
		values(triplestore,r,resourceService,l,0);
		return l;
	}

	private void values(TripleStore tripleStore, KiWiResource r, ResourceService resourceService, List<String> l, int property) {
		KiWiUriResource ur = resourceService.getUriResource(uris.get(property));
		if(ur!=null) {
			Set<KiWiTriple> triples = tripleStore.listTriples(r,ur,null,null);
			for(KiWiTriple t : triples) {
				if(uris.size()==property+1) {
					if (t.getObject() instanceof KiWiLiteral) {
						l.add(((KiWiLiteral) t.getObject()).getContent());
					} else if (t.getObject() instanceof KiWiUriResource) {
						l.add(((KiWiUriResource) t.getObject()).getUri());
					}
				} else {
					values(tripleStore,(KiWiResource)t.getObject(),resourceService,l,property+1);
				}
			}
		}
	}

	public void add(String uri) {
		uris.add(uri);
	}

	public String toString() {
		StringBuilder b = new StringBuilder();
		for(int i = 0; i < uris.size(); i++) {
			b.append(uris.get(i));
			if(i<uris.size()-1) b.append(" ? ");
		}
		b.append("(");
		b.append(type);
		b.append(")");
		return b.toString();
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTypePrefix() {
		return TYPE_PREFIX.get(type);
	}
}
